package com.jzy.hzit.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzy.hzit.entity.LoginUser;
import com.jzy.hzit.entity.User;
import com.jzy.hzit.service.UserService;
import com.jzy.hzit.mapper.UserMapper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class UserServiceImplementation extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper; // 显式注入UserMapper，虽然ServiceImpl已经隐式注入了它

    @Override
    public LoginUser findById(String username, String password) {
        // 1.1 根据用户名查询用户对象
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));

        // 1.2 验证密码（假设密码已经存储为MD5加密后的值）
        if (Objects.nonNull(user) && StringUtils.isNotBlank(password)) {
            String encryptedPassword = SecureUtil.md5(password);
            if (encryptedPassword.equals(user.getPassword())) {
                LoginUser loginUser = new LoginUser();
                loginUser.setUser(user);
                loginUser.setUserId(String.valueOf(user.getId()));
                return loginUser;
            }
        }

        return null; // 用户名或密码错误，返回null
    }

    @Override
    public boolean saveUserMsg(User user) {
        // 校验用户对象和密码不为空
        if (Objects.nonNull(user) && StringUtils.isNotBlank(user.getPassword())) {
            // 1. 对密码进行MD5加密
            String encryptedPassword = SecureUtil.md5(user.getPassword());
            user.setPassword(encryptedPassword);

        }

        boolean i = this.save(user);
        return i;
    }
}




